package ro.isdc.training.ejb3.systemuser.service.ejb;

import javax.annotation.security.RolesAllowed;
import javax.ejb.EJB;
import javax.ejb.Remote;
import javax.ejb.Stateless;
import javax.ejb.TransactionAttribute;
import javax.ejb.TransactionAttributeType;
import javax.ejb.TransactionManagement;
import javax.ejb.TransactionManagementType;

import ro.isdc.training.ejb3.systemuser.dao.SystemUserDAO;
import ro.isdc.training.ejb3.systemuser.domain.SystemUser;
import ro.isdc.training.ejb3.systemuser.service.SystemUserService;
import ro.isdc.training.ejb3.systemuser.service.domain.CreateSystemUserRequest;
import ro.isdc.training.ejb3.systemuser.service.domain.CreateSystemUserResponse;

/**
 * System user service bean implementation.
 * 
 * Remarks:
 *  - Transactions are by default CONTAINER managed, so it is not necessary
 *    to annotate the class as below.
 *  - This bean is remote as it will be accessed from outside. For future reuse
 *    in case another implementation of the service will be needed, the @Remote
 *    annotation is specified on the bean class (it is also legal to specify it
 *    on the interface).
 *  - The transaction attribute can be both specified on the class(applies to all
 *    methods) or on a method individually. The REQUIRED attribute applies by default
 *    if nothing is specified and there is container transaction demarcation.
 *  - The name of the bean is specified on the @Stateless annotation to override
 *    the "SystemUserServiceBean" bean name generated by default
 *  - By default, the bean will be bound to the following JNDI name:
 *    java:/[Name_of_EAR]/[Name_of_Bean]/[local/remote] 
 *    (i.e. java:/advancedejb3-ear-0.0.1/SystemUserServiceBean/remote).
 *    For a better management and customization we will override this default JNDI mapping
 *    in the proprietary vendor deployment descriptor (i.e. jboss.xml)
 * 
 * @author Andrei Chirila
 */
@Stateless(name="SystemUserService")
@Remote(SystemUserService.class)
@TransactionManagement(TransactionManagementType.CONTAINER)
@RolesAllowed("ADMIN")
public class SystemUserServiceBean implements SystemUserService {
  
  /**
   * System user DAO bean injected, used locally.
   */
  @EJB
  private SystemUserDAO systemUserDAO;
  
  /**
   * {@inheritDoc}
   */
  @TransactionAttribute(TransactionAttributeType.REQUIRED)
  public CreateSystemUserResponse createSystemUser(
      final CreateSystemUserRequest serviceRequest) {
    
    SystemUser systemUser = serviceRequest.getSystemUser();
    
    systemUserDAO.save(systemUser);
    
    CreateSystemUserResponse serviceResponse = new CreateSystemUserResponse();
    serviceResponse.setSystemUser(systemUser);
      
    return serviceResponse;
  }

}
